console.log("add_edit.js------add_edit.js------add_edit.js")

const split_str = "______________===8coHX858S8cNx3jAUcU8ZaRyHhdr6mVYD48QBzwtpExkb2am===_____________";

function add_and_edit(eee) {
    document.getElementById("add_and_update_box").classList.toggle("hidden")
    let typee = eee.innerText;
    if (typee === "Add_File") {
        document.getElementById("file_typeee").innerText = "Add_File";
        document.getElementById("titleee").value = "";
        document.getElementById("content_box").innerText = "";
        document.getElementById("content_box").innerHTML = "";
    }
    if (typee.includes(".txt")) {
        document.getElementById("file_typeee").innerText = typee;
        get_data_by_file_id(typee);
    }
}


function get_data_by_file_id(file_name) {
    let api_url = "/admin/edit/" + file_name;
    console.log(api_url)
    fetch(api_url, {
        method: 'GET',
        headers: {'Content-Type': 'application/json',},
    })
        // .then(response => response.json())  // 解析响应为 json, 无需再 JSON.parse() 解析
        .then(response => response.text())  // 解析响应为 文本
        .then(data => {
            // console.log(data);
            let title = data.split(split_str)[0].trim();
            let content = data.split(split_str)[1].trim();
            console.log(title)
            console.log(content)
            document.getElementById('titleee').value = title;
            document.getElementById('content_box').innerText = content;
        })
        .catch((error) => {
            console.error('Error:', error);
            alert("error---error----error")
        });
}



function Add_and_Update_file() {
    let file_name = document.getElementById("file_typeee").innerText;
    let title = document.getElementById('titleee').value;
    let content = document.getElementById('content_box').innerText;
    if (title.length < 5) {
        alert("title 内容太短");
        return false;
    }
    if (content.length < 5) {
        alert("content 内容太短");
        return false;
    }

    let api_url = "";
    if (file_name === "Add_File"){
        api_url = "/admin/add";   // 如果是 django 后端一定需要加上 / 反斜杠
    }
    if (file_name.includes(".txt")){
        api_url = "/admin/update";   // 如果是 django 后端一定需要加上 / 反斜杠
    }

    let postObj = {
        file_name:file_name,
        title: title,
        content: content,
    };
    fetch(api_url, {
        method: 'POST',
        headers: {'Content-Type': 'application/json',},
        body: JSON.stringify(postObj),
    })
        // .then(response => response.json())  // 解析响应为 json, 解析响应为 json, 无需再 JSON.parse() 解析
        .then(response => response.text())  // 解析响应为 文本
        .then(data => {
            console.log(data);
            // alert(data)
            if (data === "true"){
                location.reload()
            }
        })
        .catch((error) => {
            console.error('Error:', error);
        });
}

